<script setup>

import {inject, onMounted, provide, reactive, ref, toRefs} from "vue";
import {ElMessage} from "element-plus";
import {useItem} from "../../../../store/index.js";
import {getConfigMapListHandler as getList } from "../../../../api/configMap.js";
import {deleteTableRow} from "../../../../utils/utils.js";
import Oct2Decimal from "./Oct2Decimal.vue";

const useItemer =useItem()

const props = defineProps({
  volumeConfig: {
    type: Object,
    default: {}
  },
  method: {
    type: String,
    default: "Create"
  },
  // clusterId: {
  //   type: String,
  //   required: true
  // },
  // namespace: {
  //   type: String,
  //   required: true
  // },
})

onMounted(()=>{
  if(props.method !== "Create"){
    data.newVolumeConfig = props.volumeConfig
  }
})

const data=reactive({
  newVolumeConfig:{
    // volume名称
    name: '',
    configMap: {
      // configMap的名称
      name: '',
      defaultMode: 420,
      items: [],
      optional: true
    },
  },
  rules: {
    name: [
      {required: true,message: '请输入Volume名称',trigger: 'blur'},
    ],
    'configMap.name': [
      {required: true,message: '请选择configMap',trigger: 'blur'},
    ],
    items: {
      key: [
        {required: true,message: '请输入ConfigMap Key',trigger: 'blur'},
      ],
      path: [
        {required: true,message: '请输入ConfigMap挂载路径',trigger: 'blur'},
      ],
    },
  },
  items: []
})
let formRef =ref()
// 添加按钮触发的动作
const submit= ()=>{
  // 1. 提交前校验数据
  formRef.value.validate((valid) => {
    if (valid){
      console.log('data.newVolumeConfig',data.newVolumeConfig)
      if (useItemer.item.spec.template.spec.volumes === undefined){
        useItemer.item.spec.template.spec.volumes = []
      }
      // voluem的名称不可以重复，遍历当前环境中volume的name字段是否重复
      for (let i=0;i<useItemer.item.spec.template.spec.volumes.length;i++){
        if(useItemer.item.spec.template.spec.volumes[i].name === data.newVolumeConfig.name){
          // 说明已经存在已经相同名字的volues
          ElMessage.error("volume名称不能重复")
          return
        }
      }

      const newVlume = JSON.parse(JSON.stringify(data.newVolumeConfig))
      // data.newVolumeConfig 是引用类型，每次添加都会覆盖这个值
      useItemer.item.spec.template.spec.volumes.push(newVlume)
      console.log('data.newVolumeConfig',useItemer.item)
      // 关闭dialog
      closeDialog()
    }else {
      ElMessage.warning('请完善表单')
    }
  })
}

// 选择框展开调用接口查询数据
const visibleChanged=(visible)=>{
  if (visible){
    // 调用查询类别函数
    const getData = {
      clusterId: useItemer.clusterId,
      namespace: useItemer.namespace,
    }
    getList(getData).then((response)=>{
      data.items =  response.data.data.items
      console.log("data.items",data.items)
    })
  }
}

const activeName = ref('basic')
// 添加item
const addItem= ()=>{
      const item= {
        key: "",
        path: "",
        mode: null,
      }
      data.newVolumeConfig.configMap.items.unshift(item)
}


// 订阅关闭dialog的方法
const closeDialog = inject('closeAddVolumeDialog')

const {newVolumeConfig,items,rules}=toRefs(data)
</script>

<template>
  <el-form :model="newVolumeConfig" ref="formRef" :rules="rules">
    <el-tabs v-model="activeName" class="demo-tabs" >
      <el-tab-pane label="基本配置" name="basic">
        <!--   名称     -->
        <el-row :gutter="20">
          <!-- 存储名称 -->
          <el-col :span="7"  v-if="props.method ==='Create'">
            <el-form-item label="Volume名称" prop="name" required>
              <el-input  v-model.trim="newVolumeConfig.name" style="width: 180px" placeholder="请输Volume名称"/>
            </el-form-item>
          </el-col>
          <!--    ClaimName      -->
          <el-col :span="7">
            <el-form-item label="ConfigMap" prop="configMap.name" required>
              <!--          <el-input  v-model.trim="newVolumeConfig.persistentVolumeClaim.claimName" style="width: 180px" placeholder="请输宿主机路径"/>-->
              <el-select v-model="newVolumeConfig.configMap.name" placeholder="请选择ConfigMap" style="width: 240px" @visible-change="visibleChanged">
                <el-option
                    v-for="item in items"
                    :key="item.metadata.name"
                    :label="item.metadata.name"
                    :value="item.metadata.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- NFS只读按钮 -->
          <el-col :span="4">
            <el-form-item label="Key必须存在"  title="当指定item时，是否要求key必须存在"  prop="configMap.optional">
              <!--          <el-input  v-model.trim="newVolumeConfig.nfs.readOnly" style="width: 180px" placeholder="请输宿主机路径"/>-->
              <el-switch v-model="newVolumeConfig.configMap.optional" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="默认挂载权限"   prop="configMap.defaultMode">
                <Oct2Decimal v-model:data="newVolumeConfig.configMap.defaultMode"></Oct2Decimal>
<!--              <el-input-number :controls="false" v-model="newVolumeConfig.configMap.defaultMode"  />-->
            </el-form-item>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="自定义挂载路径" name="items">
        <el-table :data="newVolumeConfig.configMap.items" border style="height: 240px">
            <el-table-column label="Key" width="340px" align="center">
                <template #default=scope>
                   <!-- scope.$index: 当前行 -->
                   <!-- configMap.items.2.key -->
                   <!-- configMap.items.2.value -->
                   <el-form-item label="" :prop="('configMap.items.'+scope.$index+'.key')" required :rules="rules.items.key">
                     <el-input v-model.trim="scope.row.key" placeholder="请输入ConfigMap键的名称"></el-input>
                   </el-form-item>
                </template>
            </el-table-column>
            <el-table-column label="挂载路径" width="440px" align="center" style="height: 140px">
              <template #default=scope>
                <el-form-item label="" :prop="('configMap.items.'+scope.$index+'.path')" required :rules="rules.items.path">
                  <el-input v-model.trim="scope.row.path" placeholder="请输入挂载的相对路径"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="挂载权限" width="140px" align="center">
              <template #default=scope>
                <el-form-item label="" >
                  <Oct2Decimal v-model:data="scope.row.mode" ></Oct2Decimal>
                  <!--   <el-input v-model.trim="scope.row.mode"></el-input>   -->
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column width="" align="center">
              <template #header>
                <el-button link type="primary" @click="addItem()">添加</el-button>
              </template>
              <template #default=scope >
                <el-button link type="warning" @click="deleteTableRow(newVolumeConfig.configMap.items,scope.$index)">删除</el-button>
              </template>
            </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <!--  提交按钮  -->
    <div class="button-container"  v-if="props.method ==='Create'" style="margin-top: 14px">
      <el-button  @click="submit()" type="primary">添加</el-button>
    </div>
  </el-form>
</template>

<style scoped>
/* el-button 剧中存放 */
.button-container {
  display: flex;
  justify-content: center; /* 水平居中 */
}
</style>